package is.api.demo.isgateway.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import is.api.demo.isgateway.support.*;
import org.apache.http.HttpStatus;
import org.bouncycastle.crypto.InvalidCipherTextException;

import java.util.Objects;

/**********************************************************************
 * &lt;p&gt;文件名：IsGatewayApiResponseUtils.java &lt;/p&gt;
 * &lt;p&gt;文件描述：(描述该文件做什么) 
 * @project_name：rest-api-demo
 * @author zengshunyao
 * @create 2025/11/27 16:48
 * @history
 * @department：政务事业部
 * Copyright ChengDu Funi Cloud Code Technology Development CO.,LTD 2014 
 *                    All Rights Reserved.
 */
public abstract class IsGatewayApiResponseUtils {
    private final static String SUCCESS = "success";
    private final static String FAIL = "fail";
    //
    private static final ObjectReader objectReader;

    static {
        ObjectMapper objectMapper = new ObjectMapper();
        objectReader = objectMapper.reader();
        //忽略未知字段，全局忽略
        //objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    /**
     * 获取响应报文
     *
     * @param isGateWayHttpResponseBody
     * @param privateKeyStrFromPKCS8
     */
    public static ResponseBody obtainResponse(final IsGateWayHttpResponseBody isGateWayHttpResponseBody,
                                              final String privateKeyStrFromPKCS8) throws InvalidCipherTextException, JsonProcessingException {
        if (!Objects.equals(isGateWayHttpResponseBody.getStatusCode(), HttpStatus.SC_OK)) {
            throw new IllegalStateException("接口返回异常,statusCode=" + isGateWayHttpResponseBody.getStatusCode());
        }
        //报文是否加密
        final boolean decryptedTag = IsGateWayMediaTypeUtils.isApplicationJson(isGateWayHttpResponseBody.getAllHeaders());
        //反序列化
        final IsGatewayApiResponse isGatewayApiResponse = objectReader.forType(IsGatewayApiResponse.class).readValue(isGateWayHttpResponseBody.getResponseBody());

        final ResponseBody responseBody = new ResponseBody();
        responseBody.setCode(FAIL);
        responseBody.setMessage(isGatewayApiResponse.getMessage());

        //以下4.0标准接口
        if (IsGateWayStringUtils.hasText(isGatewayApiResponse.getCode())) {
            responseBody.setMessage(isGatewayApiResponse.getMessage());
            //响应体解密
            if (OpenResponseCodeEnum.isOk(isGatewayApiResponse.getCode())) {
                responseBody.setCode(SUCCESS);
                responseBody.setMessage(isGatewayApiResponse.getMessage());
                //业务数据节点
                final Object encryptData = isGatewayApiResponse.getData();
                if (Objects.isNull(encryptData)) {
                    System.err.println("返回报文为空");
                    responseBody.setData(null);
                    responseBody.setResultDetail(null);
                    return responseBody;
                }
                if (Objects.isNull(privateKeyStrFromPKCS8)) {
                    System.err.println("私钥不存在，privateKeyStrFromPKCS8=" + privateKeyStrFromPKCS8);
                    responseBody.setData(null);
                    responseBody.setResultDetail(null);
                    return responseBody;
                }
                if (decryptedTag) {
                    //业务数据节点 利用私钥 解析为明文
                    final String plainData = Sm2Utils.decrypt(privateKeyStrFromPKCS8, String.valueOf(encryptData));
                    responseBody.setResultDetail(plainData);
                    responseBody.setData(plainData);
                } else {
                    responseBody.setResultDetail(JSON.toJSONString(encryptData));
                    responseBody.setData(encryptData);
                }
            } else {
                responseBody.setCode(FAIL);
                final String responseTextByCode = OpenResponseCodeEnum.getResponseTextByCode(isGatewayApiResponse.getCode());
                responseBody.setMessage(isGatewayApiResponse.getMessage());
                System.err.println(responseTextByCode);
                //异常
                System.err.println(isGatewayApiResponse.getErrorDetail());
            }
            return responseBody;
        }

        //以下2.0接口标准
        if (IsGateWayStringUtils.hasText(isGatewayApiResponse.getStatus())) {
            //响应体解密
            if (RestResponseCodeEnum.isSuccess(isGatewayApiResponse.getStatus())) {
                responseBody.setCode(SUCCESS);
                responseBody.setMessage(isGatewayApiResponse.getMessage());
                //业务数据节点
                final Object encryptData = isGatewayApiResponse.getResult();
                if (Objects.isNull(encryptData)) {
                    System.err.println("返回报文为空");
                    responseBody.setData(null);
                    responseBody.setResultDetail(null);
                    return responseBody;
                }
                if (Objects.isNull(privateKeyStrFromPKCS8)) {
                    System.err.println("私钥不存在，privateKeyStrFromPKCS8=" + privateKeyStrFromPKCS8);
                    responseBody.setData(null);
                    responseBody.setResultDetail(null);
                    return responseBody;
                }
                //业务数据节点 利用私钥 解析为明文
                if (decryptedTag) {
                    //业务数据节点 利用私钥 解析为明文
                    final String plainData = Sm2Utils.decrypt(privateKeyStrFromPKCS8, String.valueOf(encryptData));
                    responseBody.setResultDetail(plainData);
                    responseBody.setData(plainData);
                } else {
                    responseBody.setResultDetail(JSON.toJSONString(encryptData));
                    responseBody.setData(encryptData);
                }
                //设置结果数据
                responseBody.setResultDetail(isGatewayApiResponse.getResultDetail());
                responseBody.setData(isGatewayApiResponse.getData());
            } else {
                responseBody.setCode(FAIL);
                responseBody.setMessage(isGatewayApiResponse.getMessage());
                //异常
                System.err.println(isGatewayApiResponse.getErrorDetail());
            }
            return responseBody;
        }
        return responseBody;
    }
}
